<template>
  <div class="app-container">
    <el-card class="face-register-card">
      <template #header>
        <div class="card-header">
          <span>人脸注册</span>
        </div>
      </template>
      <div class="face-register-content">
        <!-- 摄像头区域 -->
        <div class="camera-container">
          <video id="video" ref="videoRef" class="camera-video" autoplay playsinline></video>
          <canvas id="overlayCanvas" ref="overlayCanvasRef" class="face-overlay"></canvas>
          <canvas id="captureCanvas" ref="captureCanvasRef" style="display: none;"></canvas>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
            type="primary"
            @click="startCamera"
            :disabled="cameraActive"
          >
            <span class="status-indicator" :class="cameraActive ? 'status-active' : 'status-inactive'"></span>
            {{ cameraActive ? '摄像头运行中' : '启动摄像头' }}
          </el-button>
          <el-button
            type="danger"
            @click="stopCamera"
            :disabled="!cameraActive"
          >停止摄像头</el-button>
          <el-button
            type="warning"
            @click="handleFaceRegister"
            :disabled="!cameraActive"
          >人脸注册</el-button>
        </div>

        <!-- 识别结果区域 -->
        <div class="result-section" v-if="result.message || result.user">
          <h3>识别结果</h3>
          <el-alert
            :type="result.success ? 'success' : 'error'"
            :title="result.message"
            show-icon>
          </el-alert>

          <div class="user-info" v-if="result.user && result.success">
            <img :src="result.user.faceImageUrl" alt="用户头像" class="user-avatar" v-if="result.user.faceImageUrl">
            <div>
              <p><strong>欢迎,</strong> {{ result.user.username }}</p>
              <p><strong>识别时间:</strong> {{ currentTime }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getUserProfile } from "@/api/system/user"
import { addUserFaceInfo } from "@/api/zy_my/myapi"

// 响应式数据
const cameraActive = ref(false)
const isRegistering = ref(false)
const result = reactive({
  success: false,
  user: null,
  message: ''
})
const currentTime = ref('')
const videoRef = ref(null)
const overlayCanvasRef = ref(null)
const captureCanvasRef = ref(null)

// 摄像头相关变量
let stream = null
let overlayContext = null
let captureContext = null

// 初始化摄像头元素
const initCameraElements = () => {
  const video = videoRef.value
  const overlayCanvas = overlayCanvasRef.value
  const captureCanvas = captureCanvasRef.value

  if (video && overlayCanvas && captureCanvas) {
    overlayContext = overlayCanvas.getContext('2d')
    captureContext = captureCanvas.getContext('2d')
  }
}

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN')
}

// 开启摄像头
const startCamera = async () => {
  if (!videoRef.value) {
    ElMessage.error('无法访问摄像头：视频元素未找到')
    return
  }

  try {
    initCameraElements()

    stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 640 },
        height: { ideal: 480 }
      },
      audio: false
    })

    videoRef.value.srcObject = stream
    cameraActive.value = true

    // 等待视频元数据加载完成
    videoRef.value.addEventListener('loadedmetadata', () => {
      // 设置canvas尺寸与视频一致
      if (overlayCanvasRef.value && captureCanvasRef.value) {
        overlayCanvasRef.value.width = videoRef.value.videoWidth
        overlayCanvasRef.value.height = videoRef.value.videoHeight
        captureCanvasRef.value.width = videoRef.value.videoWidth
        captureCanvasRef.value.height = videoRef.value.videoHeight
      }
    })

    ElMessage.success('摄像头已启动')
  } catch (err) {
    console.error('无法访问摄像头:', err)
    ElMessage.error('无法访问摄像头，请检查权限设置')
  }
}

// 关闭摄像头
const stopCamera = () => {
  if (stream) {
    const tracks = stream.getTracks()
    tracks.forEach(track => track.stop())
    if (videoRef.value) {
      videoRef.value.srcObject = null
    }
    cameraActive.value = false
    ElMessage.info('摄像头已停止')
  }
}

// 人脸注册处理
const handleFaceRegister = async () => {
  if (!cameraActive.value) {
    ElMessage.warning('请先启动摄像头')
    return
  }

  // 设置注册标志，防止自动识别干扰
  isRegistering.value = true

  // 声明loading变量
  let loading

  try {
    // 捕获当前帧
    if (captureCanvasRef.value && videoRef.value) {
      captureContext.drawImage(videoRef.value, 0, 0, captureCanvasRef.value.width, captureCanvasRef.value.height)

      // 先进行人脸检测并绘制人脸框
      const blobForDetection = await new Promise(resolve => {
        captureCanvasRef.value.toBlob(resolve, 'image/jpeg', 0.8)
      })

      let faceDetected = false
      if (blobForDetection) {
        // 模拟人脸检测过程
        // 这里应该调用实际的人脸检测API
        ElMessage.success('检测到人脸')
        faceDetected = true
      }

      // 如果没有检测到人脸，提示用户
      if (!faceDetected) {
        ElMessage.warning('未检测到人脸，请确保脸部在摄像头范围内')
        isRegistering.value = false
        return
      }

      // 等待一小段时间让用户看到人脸框，然后再显示加载
      await new Promise(resolve => setTimeout(resolve, 1000))

      loading = ElLoading.service({
        lock: false, // 不锁定整个界面
        text: '正在注册人脸信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)',
        customClass: 'small-loading' // 自定义样式类
      })

      // 清除人脸框
      if (overlayContext && overlayCanvasRef.value) {
        overlayContext.clearRect(0, 0, overlayCanvasRef.value.width, overlayCanvasRef.value.height)
      }

      // 将图像转换为Blob用于注册
      const blobForRegistration = await new Promise(resolve => {
        captureCanvasRef.value.toBlob(resolve, 'image/jpeg', 0.8)
      })

      if (!blobForRegistration) {
        ElMessage.error('图像捕获失败')
        isRegistering.value = false
        loading.close()
        return
      }

      // 构造FormData并调用注册API
      const formData = new FormData()
      formData.append('faceImage', blobForRegistration, 'face.jpg')

      // 调用API进行人脸注册
      const response = await addUserFaceInfo(formData)
      
      // 调试输出 - 查看实际返回的数据
      console.log('注册接口返回的完整响应:', response);

      // 检查响应是否成功 - 直接检查返回的对象是否有必需字段
      if (response && response.userName && response.faceImageUrl) {
        ElMessage.success('人脸注册成功')

        // 更新结果区域显示注册成功信息
        result.success = true
        // 使用注册返回的RegistSuccess对象中的数据
        result.user = {
          username: response.userName,
          faceImageUrl: response.faceImageUrl,
          id: null // 后端未返回用户ID，可设为null或从其他地方获取
        }
        result.message = '人脸注册成功'
        updateCurrentTime()
      } else {
        // 处理各种失败情况
        const errorMsg = response?.msg || response?.message || '人脸注册失败'
        ElMessage.error('人脸注册失败: ' + errorMsg)
        result.success = false
        result.user = null
        result.message = '人脸注册失败: ' + errorMsg
      }
    }
  } catch (error) {
    console.error('注册请求失败:', error)
    ElMessage.error('网络请求失败: ' + error.message)
    result.success = false
    result.user = null
    result.message = '网络请求失败: ' + error.message
  } finally {
    // 清除注册标志
    isRegistering.value = false
    // 关闭加载提示（如果已创建）
    if (loading) {
      loading.close()
    }
  }
}

// 组件卸载时清理资源
onUnmounted(() => {
  stopCamera()
})

// 初始化
onMounted(() => {
  // 可以在这里添加初始化逻辑
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.face-register-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.camera-container {
  position: relative;
  text-align: center;
  margin-bottom: 30px;
}

.camera-video {
  width: 100%;
  max-width: 640px;
  height: 480px;
  background-color: #000;
  border-radius: 8px;
  object-fit: cover;
}

.face-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.action-buttons {
  text-align: center;
  margin: 20px 0;
}

.result-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-right: 20px;
  object-fit: cover;
}

.status-indicator {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-active {
  background-color: #67c23a;
}

.status-inactive {
  background-color: #f56c6c;
}

.auto-detect-label {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 15px 0;
}

/* 自定义加载提示样式 */
.small-loading .el-loading-spinner {
  margin-top: -20px !important;
  font-size: 30px !important;
}

.small-loading .el-loading-text {
  font-size: 14px !important;
  margin: 8px 0 !important;
  color: #606266 !important;
}
</style>